package com.example.weddingapp.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.lifecycle.AndroidViewModel;


import com.example.weddingapp.R;
import com.example.weddingapp.base.BaseActivity;
import com.example.weddingapp.base.BaseObserver;
import com.example.weddingapp.databinding.ActivityMyInfoBinding;
import com.example.weddingapp.utils.ImageLoaderUtil;

import java.io.FileNotFoundException;
import java.util.List;

import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import cn.leancloud.AVFile;
import cn.leancloud.AVObject;
import cn.leancloud.AVUser;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * @author 我的信息
 * @Date 2020/4/24 21:38
 * @Desc
 */
public class MyInfoActivity extends BaseActivity<AndroidViewModel, ActivityMyInfoBinding> implements View.OnClickListener {
    private static final int REQUEST_CODE_CHOOSE = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_info);
        showContentView();
        setTitle("编辑信息");
    }

    @Override
    protected void initData() {
        super.initData();
        AVUser user = AVUser.getCurrentUser();
        if (user == null) return;
        String name = user.getString("name");
        String sex = user.getString("sex");
        String age = user.getString("age");
        String nick = user.getString("nick");
        String phone = user.getString("phone");
        String sign = user.getString("sign");

        bindingView.etPhone.setText(phone);
        bindingView.etName.setText(name);
        bindingView.etSex.setText(sex);
        bindingView.etNickname.setText(nick);
        bindingView.etAge.setText(age);
        bindingView.etSign.setText(sign);

        AVFile headImg = user.getAVFile("headImg");
        if (headImg != null)
            ImageLoaderUtil.displayHeadImage(this, headImg.getUrl(), bindingView.ivHead);
    }


    @Override
    protected void initView() {
        super.initView();
        bindingView.ivHead.setOnClickListener(this);
        bindingView.etSex.setOnClickListener(this);
        bindingView.btnSave.setOnClickListener(this);

    }

    /**
     * 选择头像
     */
    private void selectImage() {
        //
        rxPermissions.request(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Boolean granted) {
                        if (granted) {
                            GalleryFinal.openGallerySingle(REQUEST_CODE_CHOOSE, mOnHanlderResultCallback);
                        } else {
                            showToast("文件权限被拒绝");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    private GalleryFinal.OnHanlderResultCallback mOnHanlderResultCallback = new GalleryFinal.OnHanlderResultCallback() {
        @Override
        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
            if (resultList != null) {
                final String photoPath = resultList.get(0).getPhotoPath();

                try {
                    AVUser currentUser = AVUser.getCurrentUser();
                    AVFile file = AVFile.withAbsoluteLocalPath(System.currentTimeMillis() + ".png", photoPath);
                    currentUser.put("headImg", file);
                    currentUser.saveInBackground().subscribe(new BaseObserver<AVObject>() {
                        @Override
                        public void onNext(AVObject avObject) {
                            ImageLoaderUtil.displayHeadImage(MyInfoActivity.this, photoPath, bindingView.ivHead);
                        }
                    });
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    showToast("上传失败");
                }

            }
        }

        @Override
        public void onHanlderFailure(int requestCode, String errorMsg) {
            showToast(errorMsg);
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_head:
                selectImage();
                break;
            case R.id.et_sex:
                selectSex();
                break;
            case R.id.btn_save:
                submit();
                break;
        }
    }

    private void selectSex() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final String[] items = new String[]{"男", "女"};
        builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
                bindingView.etSex.setText(items[i]);
            }
        });
        builder.create().show();
    }

    private void submit() {
        String nick = bindingView.etNickname.getText().toString().trim();
        if (TextUtils.isEmpty(nick)) {
            Toast.makeText(this, "昵称不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        String phone = bindingView.etPhone.getText().toString().trim();

        String age = bindingView.etAge.getText().toString().trim();

        String name = bindingView.etName.getText().toString().trim();

        String sex = bindingView.etSex.getText().toString().trim();
        String sign = bindingView.etSign.getText().toString();


        AVUser avUser = AVUser.getCurrentUser();
        if (avUser != null) {
            avUser.put("name", name);
            avUser.put("sex", sex);
            avUser.put("phone", phone);
            avUser.put("nick", nick);
            avUser.put("age", age);
            avUser.put("sign", sign);
            avUser.saveInBackground().subscribe(new BaseObserver<Object>() {
                @Override
                public void onNext(Object o) {
                    super.onNext(o);
                    Toast.makeText(MyInfoActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                    finish();
                }
            });
        }


    }
}
